package unit

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"gorm.io/gorm"
	"insighttracking/query/dao"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type ModifyUnitStatusByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewModifyUnitStatusByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ModifyUnitStatusByIdApiLogic {
	hostname, _ := os.Hostname()
	return &ModifyUnitStatusByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ModifyUnitStatusByIdApiLogic) ModifyUnitStatusByIdApi(req *types.IdReq) (resp string, err error) {
	// todo: add your logic here and delete this line
	unitEntity, err := dao.UnitEntity.WithContext(l.ctx).Where(dao.UnitEntity.ID.Eq(req.Id)).First()
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return "", errors.New("传递的id错误")
	}
	status := k.If(unitEntity.Status == 2, 1, 2)
	if _, err = dao.UnitEntity.WithContext(l.ctx).Where(dao.UnitEntity.ID.Eq(req.Id)).UpdateSimple(
		dao.UnitEntity.Status.Value(int64(status)), // 排序
	); err != nil {
		return "", errors.New("修改失败")
	}
	return "修改成功", nil
}
